package com.alibaba.citrus.ots.platform.enhance.facade.service;

import com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils;
import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.platform.enhance.repository.CustomerSaleScopeRepository;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.GetEmployeeSelectRequest;
import com.epoch.app.bcots.model.dto.GetEmployeeSelectResponse;
import com.epoch.app.bcots.model.dto.GetOrganizationSelectsRequest;
import com.epoch.app.bcots.model.dto.GetOrganizationSelectsResponse;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsplatformenhance.api.customersalescopequery.dto.BatchQueryCustomerSaleScopeRequest;
import com.epoch.app.otsplatformenhance.api.customersalescopequery.dto.QueryCustomerScopeDetailRequest;
import com.epoch.app.otsplatformenhance.api.customersalescopequery.service.CustomerSaleScopeQueryService;
import com.epoch.app.otsplatformenhance.dto.request.QuerySaleScopeRequest;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryCustomerScopeRequest;
import com.epoch.app.otsplatformenhance.model.dto.PageQueryCustomerScopeResponse;
import com.epoch.app.otsplatformenhance.sdo.CustomerSaleScopeSDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.google.common.collect.Lists;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Primary
@Service
public class CustomerSaleScopeQueryServiceImpl implements CustomerSaleScopeQueryService {

    @Resource
    private CustomerSaleScopeRepository saleScopeRepository;

    @Resource
    private OtsPlatformEnhanceService otsPlatformEnhanceService;

    @Resource
    private BaseDataService baseDataService;

    @Override
    @FacadeInvoker
    public Result<List<CustomerSaleScopeSDO>> querySaleScopeList(CustomerSaleScopeSDO saleScopeSDO) {
        List<CustomerSaleScopeSDO> saleScopeList = saleScopeRepository.queryList(saleScopeSDO);
        return Result.success(saleScopeList);
    }

    @Override
    @FacadeInvoker
    public Result<List<CustomerSaleScopeSDO>> pageQuerySaleScope(QuerySaleScopeRequest request) {
        PageResult<List<CustomerSaleScopeSDO>> saleScopeList = saleScopeRepository.pageQuery(request);
        return Result.listSuccess(saleScopeList.getContent(), saleScopeList.getTotal());
    }

    @Override
    @FacadeInvoker
    public Object queryCustomerScopeDetail(QueryCustomerScopeDetailRequest queryCustomerScopeDetailRequest) {
        String id = queryCustomerScopeDetailRequest.getId();
        if(StringUtils.isBlank(id)) {
            throw new FacadeException("OTS-01-004-02-16-009");
        }
        PageQueryCustomerScopeRequest request = new PageQueryCustomerScopeRequest();
        request.setId(id);
        PageQueryCustomerScopeResponse pageQueryCustomerScopeResponse = otsPlatformEnhanceService.pageQueryCustomerScope(request);
        if(null == pageQueryCustomerScopeResponse) {
            throw new FacadeException("OTS-01-004-02-16-015");
        }
        List<Map> resultList = pageQueryCustomerScopeResponse.getResult();
        if(CollectionUtils.isEmpty(resultList)) {
            throw new FacadeException("OTS-01-004-02-16-016");
        }
        Map customerSaleScopeMap = resultList.get(0);
        // 销售组织
        String orgSaleOrganizationCode = customerSaleScopeMap.get("orgSaleOrganizationCode").toString();

        Map<String, Object> resultMap = new HashMap<>();

        // 获取销售组织下的销售渠道列表
        List<String> channelCodeList = getList(orgSaleOrganizationCode);
        String orgSaleChannelCode = customerSaleScopeMap.get("orgSaleChannelCode").toString();
        if (CollectionUtils.isEmpty(channelCodeList) || !channelCodeList.contains(orgSaleChannelCode)) {
            customerSaleScopeMap.put("orgSalesChannelName", "");
            customerSaleScopeMap.put("orgSalesDepartmentName", "");
            customerSaleScopeMap.put("principalName", "");
            customerSaleScopeMap.put("orgSaleChannelCode", "");
            customerSaleScopeMap.put("orgSaleDepartmentCode", "");
            customerSaleScopeMap.put("principal", "");
            resultMap.put("result",customerSaleScopeMap);
            return resultMap;
        }
        // 获取销售组织下的销售渠道列表
        List<String> departmentCodeList = getList(orgSaleChannelCode);
        String orgSaleDepartmentCode = customerSaleScopeMap.get("orgSaleDepartmentCode").toString();
        if (CollectionUtils.isEmpty(departmentCodeList) || !departmentCodeList.contains(orgSaleDepartmentCode)) {
            customerSaleScopeMap.put("orgSalesDepartmentName", "");
            customerSaleScopeMap.put("principalName", "");
            customerSaleScopeMap.put("orgSaleDepartmentCode", "");
            customerSaleScopeMap.put("principal", "");
            resultMap.put("result",customerSaleScopeMap);
            return resultMap;
        }
        // 获取部门下的负责人
        GetEmployeeSelectRequest getEmployeeSelectRequest = new GetEmployeeSelectRequest();
        getEmployeeSelectRequest.setId(orgSaleDepartmentCode);
        GetEmployeeSelectResponse employeeSelect = baseDataService.getEmployeeSelect(getEmployeeSelectRequest);
        if (null == employeeSelect) {
            throw new FacadeException("OTS-01-004-02-16-017");
        }
        List employeeResult = employeeSelect.getResult();
        if (CollectionUtils.isEmpty(employeeResult)) {
            customerSaleScopeMap.put("principalName", "");
            customerSaleScopeMap.put("principal", "");
            resultMap.put("result",customerSaleScopeMap);
        }
        List<Map> employeeList = JSONObject.parseArray(JSON.toJSONString(employeeResult), Map.class);
        List<String> employeeCodeList = employeeList.stream().map(map -> map.get("value").toString()).collect(Collectors.toList());
        if (Objects.isNull(customerSaleScopeMap.get("principal"))) {
            resultMap.put("result",customerSaleScopeMap);
            return resultMap;
        }
        String principal = customerSaleScopeMap.get("principal").toString();
        if(!employeeCodeList.contains(principal)) {
            customerSaleScopeMap.put("principalName", "");
            customerSaleScopeMap.put("principal", "");
            resultMap.put("result",customerSaleScopeMap);
            return resultMap;
        }
        resultMap.put("result",customerSaleScopeMap);
        return resultMap;
    }

    @NotNull
    private List<String> getList(String parentId) {
        GetOrganizationSelectsRequest getOrganizationSelectsRequest = new GetOrganizationSelectsRequest();
        getOrganizationSelectsRequest.setParentId(parentId);
        GetOrganizationSelectsResponse organizationSelects = baseDataService.getOrganizationSelects(getOrganizationSelectsRequest);
        if (null == organizationSelects) {
            return Lists.newArrayList();
        }
        List result = organizationSelects.getResult();
        if (CollectionUtils.isEmpty(result)) {
            return Lists.newArrayList();
        }
        List<Map> list = JSONObject.parseArray(JSON.toJSONString(result), Map.class);
        List<String> codeList = list.stream().map(map -> map.get("value").toString()).collect(Collectors.toList());
        return codeList;
    }

    @Override
    public Result<List<CustomerSaleScopeSDO>> batchQueryCustomerSaleScope(BatchQueryCustomerSaleScopeRequest batchQueryCustomerSaleScopeRequest) {
        List<CustomerSaleScopeSDO> scopeSDOS = saleScopeRepository.batchQueryCustomerSaleSCope(batchQueryCustomerSaleScopeRequest);
        return Result.success(scopeSDOS);
    }
}
